// Copyright (c) 2022, hzmes and contributors
// For license information, please see license.txt

frappe.provide("erpnext.utils");

frappe.ui.form.on('SRM Purchase Delivery', {

	onload: function(frm) {
		// let is_allowed = frappe.user_roles.includes('SRM Supplier');
		// frm.set_df_property('srm_supplier', 'hidden', is_allowed);
		// frm.set_df_property('supplier_name', 'hidden', is_allowed);
	},

	refresh: function(frm) {
		// 隐藏子表中的"上传"按钮
		$(".grid-upload").hide();

		// 限制供应商角色修改采购员的送货单
		if ( frappe.user.has_role('SRM Supplier') && frm.doc.items ) {
			if (frm.doc.items[0].source_billtype == 'SRM Purchase Order') {frm.toggle_enable(['items', 'purchase_department'], 0);}
		}

		// 限制采购用户角色修改供应商的送货单
		if ( frappe.user.has_role('SRM Purchase') && frm.doc.items ) {
			if (frm.doc.items[0].source_billtype == 'SRM Supply Plan Of Supplier') {frm.toggle_enable(['items', 'purchase_department'], 0);}
		}

		// 上拉交期回复: source_billtype只能是SRM Supply Plan Of Supplier
		if ( frappe.user.has_role('SRM Supplier') ) {
			frm.add_custom_button(__('SRM Supply Plan Of Supplier'), function() {
				if (frm.doc.items != undefined && frm.doc.items.length >0 && frm.doc.items[0].source_billtype == "SRM Purchase Order") 
				{ frappe.throw("已有行记录源单是采购订单,不允许选择交期回复表") }
				else (frm.doc.items == undefined || frm.doc.items.length == 0 || (frm.doc.items.length >0 && frm.doc.items[0].source_billtype == "SRM Supply Plan Of Supplier"))
				{ 
					delivery({
						frm: frm,
						method: 'get_data_from_plan',
						args: {supplier_number: frm.doc.supplier_number}
					})
				}
			})
		}
		// 上拉采购PO: source_billtype只能是SRM Purchase Order
		if ( frappe.user.has_role('SRM Purchase') ) {
			frm.add_custom_button(__('SRM Purchase Order'), function() {
				if (frm.doc.supplier_number == undefined || !frm.doc.supplier_name)  {
					frappe.throw("必须先选择供应商")
				}
				else (frm.doc.supplier_name)
				{
					delivery({
						frm: frm,
						method: 'get_data_from_po',
						args: {supplier_number: frm.doc.supplier_number}
					})
				}
			})
		}
	},

	before_save(frm) {
		if (frm.doc.items) {
	        let group_items = [];
			let group_poentrys = [];
			frm.doc.items.forEach(row => {
				if (row.real_qty <= 0) {frappe.throw(`第 ${row.idx} 行的实发数量小于等于0, 不能保存!`);}
				else {
					// 如果已经在group_items存在,则累加数量
					let index = group_items.findIndex(item => {return item.material_number == row.material_number});
					if (index >= 0) {
						// 应数量加上
						group_items[index].qty += row.qty;
						// 实发数量加上
						group_items[index].real_qty += row.real_qty;
					}
					// group_items中插入"新物料"行: 有mpq
					else { group_items.push({"material_number": row.material_number, "qty": row.qty, "real_qty": row.real_qty, "mpq": parseInt(row.mpq) ? parseInt(row.mpq):1}) }
					
					// 如果已经在group_poentrys存在,则累加数量
					let index2 = group_poentrys.findIndex(item => {return item.po_entryid == row.po_entryid});
					if (index2 >= 0) {
						// 实发数量加上
						group_poentrys[index2].real_qty += row.real_qty;
					}
					// group_items中插入"新物料"行
					else { group_poentrys.push({"po_entryid": row.po_entryid, "po_billno": row.po_billno, "fsurplusqty": row.fsurplusqty, "real_qty": row.real_qty}) }
				
				}
			});
			console.log(group_items);
			if (group_items.length>0) {
				group_items.forEach(i => {
					// 判断是否符合最小包装规范
					if(i.real_qty % i.mpq > 0) {frappe.throw(`${i.material_number}送货数量${i.real_qty}不符合最小包装${i.mpq}规范`)}
					// 符合最小包装但有超出应发数量,超出数量大于mpq
					// 2023-04-04: 最小包装是1的可以按2%的浮动回料
					else if(i.real_qty % i.mpq == 0 && i.real_qty - i.qty > i.mpq && i.mpq > 1) {
						frappe.throw(`${i.material_number}送货数量${i.real_qty}超出应发数量${i.qty}并且大于${i.mpq}`)
					}
					else if( i.mpq == 1 &&  i.real_qty - i.qty > i.qty * 0.02) {
						frappe.throw(`${i.material_number}送货数量${i.real_qty}超出应发数量${i.qty}并且大于 2% 上浮`)
					}
				})
			}
			console.log(group_poentrys);
			if (group_poentrys.length>0) {
				group_poentrys.forEach(i => {
					// 判断是否超出订单剩余数量
					if(i.real_qty > i.fsurplusqty) {frappe.throw(`${i.po_billno}送货数量${i.real_qty}超出剩余数量${i.fsurplusqty}`)}
				})
			}
		}
	},
});

frappe.ui.form.on('SRM Purchase Delivery Sub', {
	real_qty: function(frm, cdt, cdn) {
		let row = locals[cdt][cdn];
		row.remain_qty = row.real_qty - row.check_in_qty + row.check_out_qty;
		frm.refresh_field(items);
	}
});


erpnext.utils.map_current_doc = function(opts) {
	function _map() {
		if($.isArray(cur_frm.doc.items) && cur_frm.doc.items.length > 0) {
			// remove first item row if empty
			if(!cur_frm.doc.items[0].item_code) {
				cur_frm.doc.items = cur_frm.doc.items.splice(1);
			}

			// find the doctype of the items table
			var items_doctype = frappe.meta.get_docfield(cur_frm.doctype, 'items').options;

			// find the link fieldname from items table for the given
			// source_doctype
			var link_fieldname = null;
			frappe.get_meta(items_doctype).fields.forEach(function(d) {
				if(d.options===opts.source_doctype) link_fieldname = d.fieldname; });

			// search in existing items if the source_name is already set and full qty fetched
			var already_set = false;
			var item_qty_map = {};

			$.each(cur_frm.doc.items, function(i, d) {
				opts.source_name.forEach(function(src) {
					if(d[link_fieldname]==src) {
						already_set = true;
						if (item_qty_map[d.item_code])
							item_qty_map[d.item_code] += flt(d.qty);
						else
							item_qty_map[d.item_code] = flt(d.qty);
					}
				});
			});

			if(already_set) {
				opts.source_name.forEach(function(src) {
					frappe.model.with_doc(opts.source_doctype, src, function(r) {
						var source_doc = frappe.model.get_doc(opts.source_doctype, src);
						$.each(source_doc.items || [], function(i, row) {
							if(row.qty > flt(item_qty_map[row.item_code])) {
								already_set = false;
								return false;
							}
						})
					})

					if(already_set) {
						frappe.msgprint(__("You have already selected items from {0} {1}",
							[opts.source_doctype, src]));
						return;
					}

				})
			}
		}

		return frappe.call({
			// Sometimes we hit the limit for URL length of a GET request
			// as we send the full target_doc. Hence this is a POST request.
			type: "POST",
			method: 'frappe.model.mapper.map_docs',
			args: {
				"method": opts.method,
				"source_names": opts.source_name,
				"target_doc": cur_frm.doc,
				"args": opts.args
			},
			callback: function(r) {
				if(!r.exc) {
					var doc = frappe.model.sync(r.message);
					cur_frm.dirty();
					cur_frm.refresh();
				}
			}
		});
	}

	let query_args = {};
	if (opts.get_query_filters) {
		query_args.filters = opts.get_query_filters;
	}

	if (opts.get_query_method) {
		query_args.query = opts.get_query_method;
	}

	if (query_args.filters || query_args.query) {
		opts.get_query = () => query_args;
	}

	if (opts.source_doctype) {
		const d = new frappe.ui.form.MultiSelectDialog({
			doctype: opts.source_doctype,
			target: opts.target,
			date_field: opts.date_field || undefined,
			setters: opts.setters,
			get_query: opts.get_query,
			add_filters_group: 1,
			allow_child_item_selection: opts.allow_child_item_selection,
			child_fieldname: opts.child_fielname,
			child_columns: opts.child_columns,
			size: opts.size,
			action: function(selections, args) {
				let values = selections;
				console.log(values);
				if (values.length === 0) {
					frappe.msgprint(__("Please select {0}", [opts.source_doctype]))
					return;
				}
				opts.source_name = values;
				if (opts.allow_child_item_selection) {
					// args contains filtered child docnames
					opts.args = args;
				}
				d.dialog.hide();
				_map();
			},
		});

		return d;
	}

	if (opts.source_name) {
		opts.source_name = [opts.source_name];
		_map();
	}
}

let delivery = function(opts) {
	let frm = opts.frm;
	let items_data = opts.frm.doc.items
	// 定义data变量
	let data = [];
	// data默认值: 当前供应商的全部未送明细
	// 调用py方法
	frappe.call({
		method: opts.method,
		doc: frm.doc,
		args:{ supplier_number: frm.doc.supplier_number },
		freeze: true,
		freeze_message: __("Creating..."),
		callback: function(r) {
			// data.push(r.message[0]);
			data = r.message;
			// 一个forEach搭配一个filter达到去掉已选记录
			if(items_data != undefined && items_data.length > 0) {
				items_data.forEach(i => {
					data = data.filter( item => item.source_billname != i.source_billname)
				})
			}
			// console.log(data);
		}
	}).then(()=>{
		// 定义弹窗的子表字段(有参考价值)
		const child_fields = 
		[
			{fieldtype:'Read Only',fieldname:"material_number",in_list_view: 1,read_only: 1,label: __('Material Number')}, 
			{fieldtype:'Read Only',fieldname:"material_name",read_only: 1,in_list_view: 1,label: __('Material Name')}, 
			{fieldtype:'Read Only',fieldname:"material_model",read_only: 1,in_list_view: 1,label: __('Material Model')}, 
			{fieldtype:'Read Only',fieldname:"qty",read_only: 1,in_list_view: 1,label: __('Qty'),columns: 1}, 
			{fieldtype:'Read Only',fieldname:"request_date",read_only: 1,in_list_view: 0,label: __('Request Date'),columns: 1}, 
			{fieldtype:'Read Only',fieldname:"source_billname",read_only: 1,in_list_view: 0,label: __('Row'),columns: 1}, 
			{fieldtype:'Read Only',fieldname:"po_billno",read_only: 1,in_list_view: 1,label: __('采购订单'),columns: 3}, 
			{fieldtype:'Read Only',fieldname:"po_entryid",read_only: 1,in_list_view: 0,label: __('PO ENTRYID'),columns: 1}
		];
	
		let resulte_data = [];
		// 定义Dialog
		const dialog = new frappe.ui.Dialog({
			title: __("SRM Purchase Delivery"),
			// 大窗口
			size: 'extra-large',
			// 定义弹窗的所有字段
			fields: [
				{
					fieldtype:'Data',
					fieldname:"material_model",
					// default: opts.material_model,
					read_only: 0,
					hidden: 0,
					label: __('Material Model'),
					onchange: () => {
						var material_model = cur_dialog.fields_dict.material_model.value;
						if (material_model) {
							// cur_dialog.fields_dict.delivery_items.df.data = [];
							var material_number = cur_dialog.fields_dict.material_number.value;
							var material_name = cur_dialog.fields_dict.material_name.value;
							if (material_number && material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_model && material_name) {
								resulte_data = data.filter(ele => ele.material_model.includes(material_model) && ele.material_name.includes(material_name))
							}
							else if (material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_model) {
								resulte_data = data.filter(ele => ele.material_model.includes(material_model))
							}
							console.log(resulte_data);
							cur_dialog.fields_dict.delivery_items.df.data = resulte_data;
						}
						else if (!material_model) {
							cur_dialog.fields_dict.delivery_items.df.data = data
						}
						cur_dialog.fields_dict.delivery_items.grid.refresh();
					}
				},
				{fieldtype: "Column Break"},
				{
					fieldtype:'Data',
					fieldname:"material_name",
					// default: opts.assign_qty,
					read_only: 0,
					label: __('Material Name'),
					onchange: () => {
						var material_name = cur_dialog.fields_dict.material_name.value;
						if (material_name) {
							// cur_dialog.fields_dict.delivery_items.df.data = [];
							var material_number = cur_dialog.fields_dict.material_number.value;
							var material_model = cur_dialog.fields_dict.material_model.value;
							// let resulte_data = [];
							if (material_number && material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_number && material_name) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name))
							}
							else if (material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_name) {
								resulte_data = data.filter(ele => ele.material_name.includes(material_name))
							}
							console.log(resulte_data);
							cur_dialog.fields_dict.delivery_items.df.data = resulte_data;
						}
						else if (!material_name) {
							cur_dialog.fields_dict.delivery_items.df.data = data
						}
						cur_dialog.fields_dict.delivery_items.grid.refresh();
					}
				},
				{fieldtype: "Column Break"},
				{
					fieldtype:'Data',
					fieldname:"material_number",
					// default: opts.need_date,
					read_only: 0,
					label: __('Material Number'),
					onchange: () => {
						var material_number = cur_dialog.fields_dict.material_number.value;
						if (material_number) {
							// cur_dialog.fields_dict.delivery_items.df.data = [];
							var material_name = cur_dialog.fields_dict.material_name.value;
							var material_model = cur_dialog.fields_dict.material_model.value;
							// let resulte_data = [];
							if (material_number && material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_number && material_name) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name))
							}
							else if (material_number && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_model.includes(material_model))
							}
							else if (material_number) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number))
							}
							console.log(resulte_data);
							cur_dialog.fields_dict.delivery_items.df.data = resulte_data;
						}
						else if (!material_number) {
							cur_dialog.fields_dict.delivery_items.df.data = data;
						}
						cur_dialog.fields_dict.delivery_items.grid.refresh();
					}
				},
				{fieldtype: "Column Break"},
				{
					fieldtype:'Data',
					fieldname:"po_billno",
					read_only: 0,
					label: __('SRM Purchase Order'),
					onchange: () => {
						var po_billno = cur_dialog.fields_dict.po_billno.value;
						if (po_billno) {
							// cur_dialog.fields_dict.delivery_items.df.data = [];
							var material_number = cur_dialog.fields_dict.material_number.value;
							var material_name = cur_dialog.fields_dict.material_name.value;
							var material_model = cur_dialog.fields_dict.material_model.value;
							// let resulte_data = [];
							if (material_number && material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name) && ele.material_model.includes(material_model) && ele.po_billno.includes(po_billno))
							}
							else if (material_number && material_name) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name) && ele.po_billno.includes(po_billno))
							}
							else if (material_number && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_model.includes(material_model) && ele.po_billno.includes(po_billno))
							}
							else if (material_number) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.po_billno.includes(po_billno))
							}
							else {resulte_data = data.filter(ele => ele.po_billno.includes(po_billno))}
							console.log(resulte_data);
							cur_dialog.fields_dict.delivery_items.df.data = resulte_data;
						}
						else if (!po_billno) {
							cur_dialog.fields_dict.delivery_items.df.data = data;
						}
						cur_dialog.fields_dict.delivery_items.grid.refresh();
					}
				},
				{fieldtype: "Section Break"},
				// 定义弹窗中的表字段(很有参考价值)
				{
					fieldname: "delivery_items",
					// 通过fieldtype定义
					fieldtype: "Table",
					label: "Items",
					cannot_add_rows: 1,
					in_place_edit: true,
					read_only: 1,
					reqd: 1,
					data: data,
					// get_data: () => {
					// 	return data;
					// },
					fields: child_fields
				},
			],
			
			primary_action: function() {
				// 变量定义
				let items_selected = [];
				// 获取窗口中的子表明细
				items_selected = cur_dialog.fields_dict.delivery_items.grid.get_selected_children()
				items_selected.forEach(item => {frm.add_child('items',item);});
				// 2023-09-11修订: 选单返回items时第一行是空白行要删除掉
				// frm.get_field("items").grid.get_grid_row("new-srm-purchase-delivery-sub-1").remove();
				// 2023-09-14修订: 9.11没有if判断造成二次选单时remove()报错, 客户端点"获取"没有反应
				if (frm.get_field("items").grid.get_grid_row("new-srm-purchase-delivery-sub-1")) {frm.get_field("items").grid.get_grid_row("new-srm-purchase-delivery-sub-1").remove();}
				frm.refresh_field("items");
				
				this.hide();
			},
			primary_action_label: __('Get')
		});


	dialog.show();
	})
	
}



// 选择采购订单
		// frm.add_custom_button(__('Purchase Order'),
		// 	function() {
		// 		erpnext.utils.map_current_doc({
		// 			method: "srm.srm.doctype.srm_purchase_order.srm_purchase_order.make_purchase_delivery_from_po",
		// 			source_doctype: "SRM Purchase Order",
		// 			target: me.frm,
		// 			setters: [
		// 				{
		// 					label: "Supplier",
		// 					fieldname: "srm_supplier",
		// 					fieldtype: "Link",
		// 					options: "SRM Supplier",
		// 					default: me.frm.doc.srm_supplier || undefined
		// 				}
		// 			],
		// 			get_query_filters: {
		// 				// company: me.frm.doc.company,
		// 				// 未关闭且已提交
		// 				doc_closed: 'A',
		// 			},
		// 			allow_child_item_selection: true,
		// 			child_fielname: "purchase_order_sub",
		// 			child_columns: ["material_number", "qty", "material_model"],
		// 			size: "large"
		// 		})
		// 	}, __("上拉选单"));
		
		// 选择交期回复单
		// frm.add_custom_button(__('SRM Supply Plan Of Supplier'),
		// function() {
		// 	erpnext.utils.map_current_doc({
		// 		method: "srm.srm.doctype.srm_supply_plan_of_supplier.srm_supply_plan_of_supplier.make_purchase_delivery_from_plan",
		// 		source_doctype: "SRM Supply Plan Of Supplier",
		// 		target: me.frm,
		// 		setters: [
		// 			{
		// 				label: "Supplier",
		// 				fieldname: "supplier_number",
		// 				fieldtype: "Link",
		// 				options: "SRM Supplier",
		// 				default: me.frm.doc.supplier_number || undefined
		// 			}
		// 		],
		// 		get_query_filters: {
		// 			// company: me.frm.doc.company,
		// 			// 已提交且采购确认过
		// 			is_answer: 1,
		// 			// docstatus: 1,
		// 		},
		// 		allow_child_item_selection: true,
		// 		child_fielname: "orderitem",
		// 		child_columns: ["material_number", "material_name"]
		// 	})
		// }, __("上拉选单"));